var images = require("images");
var fs = require('fs');

function windowPath2UnixPath(path) {
    return path.split('\\').join('/');
}

images.setLimit(99999,99999);
function compressPng(path) {
    path = windowPath2UnixPath(path);
    //文件名排序
    var files = fs.readdirSync(path);
    files = files.sort(function (a, b) {
        var string = a.substring(0, a.indexOf("."));
        var string1 = b.substring(0, b.indexOf("."));
        var number = string - string1;
        if (isNaN(number)) {
            return -1;
        }
        return number;
    });

    //小图拼接成大图
    var img = images.createImage(1, 1);
    var currentLineW = 0;//当前行宽度
    var currentLineH = 0;//当前行高度
    var json = {};

    json["file"] = path.substring(path.lastIndexOf("/") + 1);

    //计算一个合适的图片最大宽度, 对文件数求平方根*100
    var maxWidth = Math.sqrt(files.length) * 256;
    maxWidth = Math.min(maxWidth, 9999);

    //九宫格顺序追加合成图片
    var frameArray = [];
    for (var i = 0; i < files.length; i++) {
        var w = img.width();
        var h = img.height();//line
        var temp = images.loadFromFile(path + "/" + files[i]);
        var x, y;
        //超过最大宽度换行
        if ((currentLineW + temp.width()) > maxWidth) {//to new line
            currentLineW = 0;//重置当前行的宽度和高度
            currentLineH = temp.height();
            h += temp.height();//高度增加一行
        } else {
            //整体高度微调
            h = (h - currentLineH) + Math.max(currentLineH, temp.height());
            currentLineH = Math.max(currentLineH, temp.height());
        }
        //当前宽度增加一张图的宽度
        currentLineW += temp.width();

        w = Math.max(currentLineW, w);

        //当前追加图片的xy
        x = currentLineW - temp.width();
        y = h - temp.height();

        // console.log("[INFO] currentLine " + currentLineW + "," + currentLineH );
        console.log("[INFO] " + i + " resize " + w + "," + h + " at [" + x + ":" + y);
        //拼接图片
        var newImg = images.createImage(w, h);
        newImg.draw(img, 0, 0);
        newImg.draw(temp, x, y);
        img = newImg;
        // console.log("[INFO] append " + files[i] + ":" + temp.width() + "," + temp.height());

        //记录图片在大图中的位置和图片名
        var j = {};
        j["" + files[i].substring(0, files[i].indexOf("."))] = {x: x, y: y, w: temp.width(), h: temp.height()};
        frameArray.push(j);
    }


    json["frames"] = frameArray;

    img.save(path + '.png', {quality: 100});
    fs.writeFileSync(path + ".json", JSON.stringify(json));
    console.log("[INFO] save to : " + path + '.png');
    console.log("[INFO] save json to : " + path + ".json");
}

var paths = [
    // "D:\\M2\\M2\\ChrSel.wil",
    // "D:\\M2\\M2\\Weapon.wil",
    // "D:\\M2\\M2\\Hum.wil",
    // "D:\\M2\\M2\\MagIcon.wil",
    // "D:\\M2\\M2\\Mon1.wil",
    // "D:\\M2\\M2\\Magic.wil",
    // "D:\\M2\\M2\\DnItems.wil",
    // "D:\\M2\\M2\\SmTiles.wil",
    // "D:\\M2\\M2\\Effect.wil",
    // "D:\\M2\\M2\\HumEffect.wil",
    // "D:\\M2\\M2\\stateitem.wil",
    // "D:\\M2\\M2\\mmap.wil",
    // "D:\\M2\\M2\\Objects.wil",
    // "D:\\M2\\M2\\Tiles.wil",
    // "D:\\M2\\M2\\npc.wil",
    // "D:\\M2\\M2\\Deco.wil",
    // "D:\\M2\\M2\\Hair2.wil",
    // "D:\\M2\\M2\\Dragon.wil",
    // "D:\\M2\\M2\\Hum2.wil",
    // "D:\\M2\\M2\\Weapon2.wil",
    // "D:\\M2\\M2\\Hair.wil",
];

//怪物图集
for (var j = 11; j <=18 ; j++) {
    paths.push("D:\\M2\\M2\\Objects" + j);
}
for (var i in paths) {
    try {

        compressPng(paths[i]);
    } catch (e) {
        console.log("[ERR ]  "+JSON.stringify(e));
    }

}
